<?php

namespace App\Console\Commands\Mp;

use App\Admin\Utils\MpUtils;
use App\Jobs\Mp\FreePublishSubmitJob;
use App\Models\Posts\WxPost;
use App\Wen\Utils\Settings;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class FreePublishGenerate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mp_free_publish:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成公众号推文';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        global $__MINI_GLOBAL_PAYCODE_34__;
        if(!$__MINI_GLOBAL_PAYCODE_34__){
            _logger_(__file__, __line__, '此功能需要解锁付费34');
        }
        $tenant_alone = Settings::get('app_mp_free_publish_tenant_alone', 2);
        $post_range = Settings::get('app_mp_free_publish_post_range', 3);
        $circle_range = explode(',', Settings::get('app_mp_free_publish_circle_range', ''));
        $now = Carbon::now();

        if($tenant_alone == 1){
            $the_num = Settings::get('mp_free_publish_all_num', 1);
            // 所有一起推
            if($post_range < 10){
                $threeDaysAgo = $now->subDays($post_range);
                $post_query = WxPost::withCount(['like' => function ($query) use ($threeDaysAgo) {
                    $query->where('created_at', '>=', $threeDaysAgo);
                }]);
                if(!_empty_($circle_range)){
                    $post_query = $post_query->whereIn('circle_id', $post_query);
                }
                $mostPost = $post_query->where('is_examine', 1)->where('posts_state', 0)->whereNotExists(function ($query){
                    $query->select(DB::raw(1))
                        ->from('wx_posts_meta_str')->where('meta_key', 'mp_free_publish_all')
                        ->whereRaw('wx_posts_meta_str.post_id = wx_posts.id');
                })->where('created_at', '>=', $threeDaysAgo)->orderBy('like_count', 'desc')->orderBy('id', 'desc')->limit(_between_(Settings::get('app_mp_free_publish_post_num', 10), 1, 100))->pluck('id')->toArray();
            }else{
                $post_range -= 10;
                $threeDaysAgo = $now->subDays($post_range);

                $post_query = WxPost::withCount(['comment' => function ($query) use ($threeDaysAgo) {
                    $query->where('created_at', '>=', $threeDaysAgo);
                }]);
                if(!_empty_($circle_range)){
                    $post_query = $post_query->whereIn('circle_id', $post_query);
                }
                $mostPost = $post_query->where('is_examine', 1)->where('posts_state', 0)->whereNotExists(function ($query){
                    $query->select(DB::raw(1))
                        ->from('wx_posts_meta_str')->where('meta_key', 'mp_free_publish_all')
                        ->whereRaw('wx_posts_meta_str.post_id = wx_posts.id');
                })->where('created_at', '>=', $threeDaysAgo)->orderBy('comment_count', 'desc')->orderBy('id', 'desc')->limit(_between_(Settings::get('app_mp_free_publish_post_num', 10), 1, 100))->pluck('id')->toArray();
            }
            if(!_empty_($mostPost)){
                DB::beginTransaction();
                try {
                    // todo:
                    $r = MpUtils::generate_a_push($the_num, $mostPost);
                    if($r && $r > 0){
                        Settings::set('mp_free_publish_all_num', $the_num + 1);
                        FreePublishSubmitJob::dispatch($r, 0, $mostPost, 10)->delay(now()->addMinutes(10));
                    }else{
                        _logger_(__file__, __line__, '生成公众号推文失败');
                    }
                    DB::commit();
                    return true;
                } catch (\Exception $e) {
                    DB::rollBack();
                    _logger_(__file__, __line__, $e->getMessage());
                    return false;
                }

            }
        }else if($tenant_alone == 2){
            global $__MINI_GLOBAL_TENANTS_ARR__;
            foreach ($__MINI_GLOBAL_TENANTS_ARR__ as $tenant_id){
                if($tenant_id != 999){
                    $the_num = Settings::get('mp_free_publish_'.$tenant_id.'_num', 1);
                    // 所有一起推
                    if($post_range < 10){
                        $threeDaysAgo = $now->subDays($post_range);
                        $mostPost = WxPost::withCount(['like' => function ($query) use ($threeDaysAgo) {
                            $query->where('created_at', '>=', $threeDaysAgo);
                        }])->where('is_examine', 1)->where('posts_state', 0)->where('tenant_id', $tenant_id)->whereNotExists(function ($query) use ($tenant_id){
                            $query->select(DB::raw(1))
                                ->from('wx_posts_meta_str')->where('meta_key', 'mp_free_publish_'.$tenant_id)
                                ->whereRaw('wx_posts_meta_str.post_id = wx_posts.id');
                        })->where('created_at', '>=', $threeDaysAgo)->orderBy('like_count', 'desc')->orderBy('id', 'desc')->limit(_between_(Settings::get('app_mp_free_publish_post_num', 10), 1, 100))->pluck('id')->toArray();
                    }else{
                        $post_range -= 10;
                        $threeDaysAgo = $now->subDays($post_range);
                        $mostPost = WxPost::withCount(['comment' => function ($query) use ($threeDaysAgo) {
                            $query->where('created_at', '>=', $threeDaysAgo);
                        }])->where('is_examine', 1)->where('posts_state', 0)->where('tenant_id', $tenant_id)->whereNotExists(function ($query) use ($tenant_id){
                            $query->select(DB::raw(1))
                                ->from('wx_posts_meta_str')->where('meta_key', 'mp_free_publish_'.$tenant_id)
                                ->whereRaw('wx_posts_meta_str.post_id = wx_posts.id');
                        })->where('created_at', '>=', $threeDaysAgo)->orderBy('comment_count', 'desc')->orderBy('id', 'desc')->limit(_between_(Settings::get('app_mp_free_publish_post_num', 10), 1, 100))->pluck('id')->toArray();
                    }
                    if(!_empty_($mostPost)){
                        DB::beginTransaction();
                        try {
                            // todo:
                            $r = MpUtils::generate_a_push($the_num, $mostPost);
                            if($r && $r > 0){
                                Settings::set('mp_free_publish_'.$tenant_id.'_num', $the_num + 1);
                                update_object_meta(1, $r, 'from_tenant', $tenant_id, 'n');
                                FreePublishSubmitJob::dispatch($r, $tenant_id, $mostPost, 10)->delay(now()->addMinutes(10));
                            }else{
                                _logger_(__file__, __line__, '生成分站'.$tenant_id.'公众号推文失败');
                            }
                            DB::commit();
                            return true;
                        } catch (\Exception $e) {
                            DB::rollBack();
                            _logger_(__file__, __line__, $e->getMessage());
                            return false;
                        }
                    }
                }
            }
        }
        return 0;
    }
}
